import React, { Component, Fragment } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { uploadUrl } from '@/config/index';
import {
  Card,
  Tabs,
  message,
  Button,
  Table,
  Select,
  Modal,
  Form,
  Input,
  Icon,
  Upload,
  Popconfirm,
  Divider,
  Row,
  Col,
  Checkbox,
  Alert,
} from 'antd';
import { connect } from 'dva';
import commonApi from '@/services/common';
import Products from './products';
import tabService from './services';

const { TabPane } = Tabs;
const { Option } = Select;

@connect(({ tab }) => ({ ...tab }))
@Form.create()
class TabSetting extends Component {
  state = {
    onChannel: '1',
    onNewChannel: '1', // 同步tab modal用的
    tabVisible: false, // modal的控制
    title: '', // modal的标题
    imgSrc: '',
    fileList: [],
    tabActiveKey: '',
    pageNumber: 1,
    pageSize: 10,
    tabInfo: [], // 当前tab的信息
    addTabProductVisible: false,
    tabProductVisible: false,
    productInfo: {},
    waitName: [],
    loading: true,
    params: [], // 确定同步的参数
    targetChannels: [], // 要同步的渠道
    updateConfirmLoading: false,
    addTabConfirmLoading: false,
    newIndexSort: null,
    channelData: [],
    sortVisible: false,
    data: {},
  };

  columns = [
    {
      title: '商品编号',
      dataIndex: 'itemId',
      align: 'center',
      key: 'itemId',
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      align: 'center',
      key: 'name',
    },
    {
      title: '店铺名称',
      dataIndex: 'shopName',
      align: 'center',
      key: 'shopName',
    },
    {
      title: '排序',
      dataIndex: 'indexSort',
      align: 'center',
      key: 'indexSort',
    },
    {
      title: '新旧程度',
      dataIndex: 'oldNewDegree',
      align: 'center',
      key: 'oldNewDegree',
    },
    {
      title: '价格',
      dataIndex: 'price',
      align: 'center',
      key: 'price',
    },
    {
      title: '操作',
      align: 'center',
      key: 'action',
      render: (text, record) => (
        <div className="table-action">
          <a
            onClick={() =>
              this.setState({
                sortVisible: true,
                data: record,
              })
            }
          >
            排序
          </a>
          <Divider type="vertical" />
          {/* <a style={{ whiteSpace: 'nowrap' }} onClick={() => this.updateProduct(record)}>更新</a> */}
          <Popconfirm title="确定要删除吗？" onConfirm={() => this.deleteProduct(record)}>
            <a>删除</a>
          </Popconfirm>
        </div>
      ),
    },
  ];

  componentDidMount() {
    this.getTab();
    this.getChannel();
  }

  // 更新tab下的产品
  updateProduct = data => {
    const fileList = [
      {
        uid: 1,
        url: data.image,
      },
    ];

    this.setState(
      {
        tabProductVisible: true,
        productInfo: data,
        imgSrc: data.image,
        fileList,
        newIndexSort: data.indexSort,
      },
      () => {
        // this.props.form.setFieldsValue({
        //   [bb.sort]: `Hi,`,
        // });
        // (
        //   { [fieldName]: value },
        //   callback: Function
        // ) => void
      },
    );
  };

  confirmUpdate = () => {
    this.setState(
      {
        updateConfirmLoading: true,
      },
      () => {
        this.props.form.validateFields(['bb'], (err, value) => {
          if (!err) {
            this.props.dispatch({
              type: 'tab/updateProduct',
              payload: {
                name: value.bb.name,
                indexSort: value.bb.sort,
                id: this.state.productInfo.id,
                image: this.state.imgSrc,
              },
              callback: res => {
                //

                if (res.data.msg === '操作成功') {
                  this.props.form.resetFields();
                  this.setState(
                    {
                      tabProductVisible: false,
                      updateConfirmLoading: false,
                      newIndexSort: null,
                    },
                    () => this.onTabChange(this.state.tabActiveKey),
                  );
                  Modal.destroyAll();
                } else {
                  message.error(res.data.msg);
                }
              },
            });
          }
        });
      },
    );
  };

  // 删除tab下的产品
  deleteProduct = record => {
    this.setState({
      loading: true,
    });
    tabService
      .deleteProduct({
        id: record.id,
      })
      .then(res => {
        message.success('删除成功');
        this.onTabChange(this.state.tabActiveKey);
      });
  };

  // 获取上架渠道
  getChannel = () => {
    commonApi.selectPlateformChannel().then(res => {
      this.setState({
        channelData: res || [],
      });
    });
  };

  // 获取tab
  getTab = () => {
    this.props.dispatch({
      type: 'tab/getTab',
      callback: res => {
        message.success('成功获取tab');
        this.setState(
          {
            tabActiveKey: res && res.records && res.records[0] && res.records[0].id || 1,
            loading: true,
            tabInfo: res.records[0] || {},
          },
          () => {
            this.getProduct();
          },
        );
      },
    });
  };

  // 获取产品
  getProduct = () => {
    tabService
      .getProduct({
        id: this.state.tabActiveKey,
        pageSize: this.state.pageSize,
        pageNumber: this.state.pageNumber,
      })
      .then(res => {
        this.setState({
          loading: false,
          product: res.records,
          total: res.total,
          current: res.current,
        });
      });
  };

  // 页签的跳转
  onTabChange = key => {
    const tabInfo = this.props.tab.find(item => item.id === Number(key)) || {};
    this.setState(
      {
        tabActiveKey: key,
        pageSize: 10,
        pageNumber: 1,
        loading: true,
        tabInfo,
      },
      () => this.getProduct(),
    );
  };

  // 新增Tab
  addTab = () => {
    this.setState({
      tabVisible: true,
      title: '新增Tab',
    });
  };

  // 修改tab
  editTab = () => {
    const id = this.state.tabActiveKey;
    const info = this.props.tab.find(item => item.id === Number(id)) || {};
    this.setState({
      tabVisible: true,
      title: '修改tab',
      tabInfo: info,
    });
  };

  // modal的确认
  handleOk = () => {
    this.props.form.validateFields(['tab'], (err, value) => {
      if (!err) {
        this.setState({
          tabInfo: [],
          addTabConfirmLoading: true,
        });
        if (this.state.title === '新增Tab') {
          // 增加
          tabService
            .addTab(value.tab)
            .then(res => {
              this.setState(
                {
                  tabVisible: false,
                  addTabConfirmLoading: false,
                },
                () => {
                  this.props.form.resetFields();
                  this.getTab();
                },
              );
            })
            .finally(() => {
              this.setState({
                addTabConfirmLoading: false,
              });
            });
        } else {
          // 修改
          tabService
            .updateTab({
              id: this.state.tabInfo.id,
              ...value.tab,
            })
            .then(res => {
              this.setState(
                {
                  tabVisible: false,
                },
                () => {
                  this.props.form.resetFields();
                  this.getTab();
                },
              );
            })
            .finally(() => {
              this.setState({
                addTabConfirmLoading: false,
              });
            });
        }
      }
    });
  };
  onOk = e => {
    e.preventDefault();
    this.props.form.validateFields(['sort'], (err, value) => {
      if (!err) {
        tabService
          .updateIndexPrdouctSort({ indexSort: value.sort, id: this.state.data.id })
          .then(res => {
            this.setState(
              {
                sortVisible: false,
              },
              () => {
                this.onTabChange(this.state.tabActiveKey);
                message.success('修改成功。');
              },
            );
          });
      }
    });
  };
  // 上传的回调
  handleUploadChange = ({ file, fileList, event }) => {
    const filelist = [...fileList] || [];
    if (file.status == 'done') {
      filelist.map(item => {
        this.setState({
          imgSrc: item.response.data,
        });
      });
    }
    this.setState({
      fileList,
    });
  };

  // 上传后预览的回调
  handlePreview = () => {
    this.setState({
      imgVisible: true,
    });
  };

  // 上传后下载的回调
  onDownload = file => {
    return window.open(this.state.imgSrc);
  };

  // 上传后删除的回调
  onRemove = () => {
    this.setState({
      fileList: [],
      imgSrc: '',
    });
  };

  // 删除tab
  deleteTab = () => {
    tabService
      .deleteTab({
        id: this.state.tabActiveKey,
      })
      .then(res => {
        if (res.data) {
          this.getTab();
        }
      });
  };

  // 分页，下一页
  onChange = pageNumber => {
    // alert(pageNumber)
    this.setState(
      {
        pageNumber,
      },
      () => {
        this.getProduct();
      },
    );
  };

  showTotal = () => {
    return `共有${this.state.total}条`;
  };

  // 切换每页数量
  onShowSizeChange = (current, pageSize) => {
    this.setState(
      {
        pageSize,
        pageNumber: 1,
      },
      () => {
        this.getProduct();
      },
    );
  };

  // 新增tab产品
  addTabProduct = () => {
    this.setState({
      addTabProductVisible: true,
    });
  };

  tabProductCancel = () => {
    this.setState({
      addTabProductVisible: false,
    });
  };
  sortProductCancel = () => {
    this.setState({
      sortVisible: false,
    });
  };

  rulesJumpUrl = () => {
    const hostPath = `${window.location.protocol}//${window.location.host}${window.location.pathname}`;
    window.open(`${hostPath}#/ope/rule/index`);
  };

  render() {
    const {
      onChannel,
      product,
      onNewChannel,
      loading,
      tabVisible,
      addTabConfirmLoading,
      title,
      imgSrc,
      fileList,
      tabActiveKey,
      current,
      total,
      addTabProductVisible,
      tabInfo,
      tabProductVisible,
      updateConfirmLoading,
      productInfo,
      waitName,
      channelData,
    } = this.state;
    const { tab } = this.props;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const _tabInfo = this.props.tab.find(item => item.id === Number(tabActiveKey)) || {};
    const tabName = _tabInfo.name;

    console.log(3);

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    return (
      <PageHeaderWrapper
        className="nav-tab"
        title={false}
        content={
          <div>
            <div>
              <Button type="primary" className="w-112" onClick={this.addTab}>
                新增Tab
              </Button>
              <Button onClick={this.editTab} className="w-80" style={{ margin: '10px 10px' }}>
                修改Tab
              </Button>
              <Popconfirm
                title={'确定要删除' + ` ${tabName} ` + 'Tab吗？'}
                onConfirm={this.deleteTab}
              >
                <Button className="w-80">删除Tab</Button>
              </Popconfirm>
            </div>
            <Tabs size="small" onChange={this.onTabChange} animated={false}>
              {tab &&
                tab.map(item => {
                  return <TabPane tab={item.name} key={item.id} />;
                })}
            </Tabs>
          </div>
        }
      >
        <Card bordered={false} style={{ marginTop: 20 }}>
          <Button onClick={this.addTabProduct} className="mb-18 w-139">
            新增tab产品
          </Button>
          <Table
            loading={loading}
            columns={this.columns}
            dataSource={product}
            rowKey={record => record.id}
            pagination={{
              current,
              total,
              onChange: this.onChange,
              showTotal: this.showTotal,
              showQuickJumper: true,
              pageSizeOptions: ['3', '5', '10'],
              showSizeChanger: true,
              onShowSizeChange: this.onShowSizeChange,
            }}
          />
        </Card>
        {/* 新增Tab */}
        <Modal
          title={title}
          visible={tabVisible}
          onOk={this.handleOk}
          confirmLoading={addTabConfirmLoading}
          destroyOnClose
          onCancel={() => {
            this.setState({
              tabVisible: false,
              tabInfo: {},
              fileList: [],
              imgSrc: [],
            });
          }}
        >
          <Form {...formItemLayout}>
            <Form.Item label="上架渠道">
              {getFieldDecorator('tab.channerIds', {
                rules: [
                  {
                    required: true,
                    message: '上架渠道不能为空',
                  },
                ],
                initialValue: tabInfo.channerNames || [],
              })(
                <Select mode="multiple" style={{ width: '100%' }} placeholder="全部">
                  {channelData.map((item, sign) => {
                    return (
                      <Option key={item.appId} value={item.channelId}>
                        {' '}
                        {item.channelName}{' '}
                      </Option>
                    );
                  })}
                </Select>,
              )}
            </Form.Item>
            <Form.Item label="Tab名称">
              {getFieldDecorator('tab.name', {
                rules: [
                  {
                    required: true,
                    message: 'Tab名称不能为空',
                  },
                ],
                initialValue: tabInfo.name,
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <Form.Item label="跳转地址">
              {getFieldDecorator('tab.tabImgUrl', {
                rules: [
                  {
                    required: true,
                    message: '跳转地址不能为空',
                  },
                ],
                initialValue: tabInfo.tabImgUrl,
              })(
                // <Input addonAfter={<Icon onClick={this.rulesJumpUrl} type="question-circle" />} />
                <Input placeholder="请输入" />,
              )}
            </Form.Item>
            <Form.Item label="排序规则">
              {getFieldDecorator('tab.indexSort', {
                rules: [
                  {
                    required: true,
                    message: '排序不能为空',
                  },
                ],
                initialValue: tabInfo.indexSort,
              })(<Input placeholder="请输入" />)}
            </Form.Item>
          </Form>
        </Modal>
        {/* 新增tab产品 */}
        <Modal
          visible={addTabProductVisible}
          title="新增Tab产品"
          footer={null}
          destroyOnClose
          onCancel={this.tabProductCancel}
          width={1000}
        >
          <Products
            tabProductCancel={this.tabProductCancel}
            onTabChange={this.onTabChange}
            tabActiveKey={tabActiveKey}
            channel={onChannel}
          />
        </Modal>
        <Modal
          visible={this.state.sortVisible}
          title="排序"
          // footer={null}
          destroyOnClose
          onCancel={this.sortProductCancel}
          // width={1000}
          onOk={this.onOk}
        >
          <Form {...formItemLayout}>
            <Form.Item label="排序">
              {getFieldDecorator('sort', {
                rules: [
                  {
                    required: true,
                    message: '排序不能为空',
                  },
                ],
                initialValue: this.state.data.indexSort || undefined,
              })(<Input placeholder="请输入" />)}
            </Form.Item>
          </Form>
        </Modal>
        {/* 更新tab下的产品 */}
        <Modal
          title={`是否更新${tabActiveKey}tab下的产品`}
          visible={tabProductVisible}
          onCancel={() => {
            this.setState({
              tabProductVisible: false,
              imgSrc: '',
              fileList: [],
              newIndexSort: null,
              // productInfo: {}
            });
            // Modal.destroyAll()
            this.props.form.resetFields();
          }}
          confirmLoading={updateConfirmLoading}
          onOk={this.confirmUpdate}
        >
          <Form {...formItemLayout}>
            <Form.Item label="name">
              {getFieldDecorator('bb.name', {
                rules: [
                  {
                    required: true,
                    message: 'name不能为空',
                  },
                ],
                initialValue: productInfo ? productInfo.name : null,
              })(<Input />)}
            </Form.Item>
            <Form.Item label="排序">
              {getFieldDecorator('bb.sort', {
                rules: [
                  {
                    required: true,
                    message: '排序不能为空',
                  },
                ],
                initialValue: productInfo.indexSort,
              })(<Input />)}
            </Form.Item>
            <Form.Item label="图片上传">
              {getFieldDecorator('bb.imgSrc', {
                rules: [
                  {
                    required: true,
                    message: '',
                  },
                  {
                    validator: (rule, value, callback) => {
                      const { form } = this.props;
                      if (!imgSrc) {
                        callback('图片不能为空');
                      }
                      callback();
                    },
                  },
                ],
                initialValue: imgSrc || null,
              })(
                <Upload
                  accept="image/*"
                  action={uploadUrl}
                  listType="picture-card"
                  fileList={fileList}
                  onPreview={this.handlePreview} // 预览
                  onRemove={this.onRemove} // 删除
                  onChange={this.handleUploadChange}
                >
                  {fileList.length >= 1 ? null : uploadButton}
                </Upload>,
              )}
            </Form.Item>
          </Form>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default TabSetting;
